package com.insurance.pingan.bid.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.insurance.pingan.bid.service.PingAnBidService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 平安接口实现类
 *
 * @version 1.0
 * @date 2020/10/17
 **/
@Slf4j
@Service
public class PingAnBidServiceImpl implements PingAnBidService {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 平安tokenMap 用于存放token
     */
    private static Map<String, String> tokenMap = new HashMap<String, String>();

    @Value("${pingan.bid.tokenUrl}")
    private String tokenUrl;

    @Value("${pingan.bid.applyForFeeUrl}")
    private String applyForFeeUrl;

    @Value("${pingan.bid.acceptForFeeUrl}")
    private String acceptForFeeUrl;

    @Value("${pingan.bid.prePayFinanceUrl}")
    private String prePayFinanceUrl;

    @Value("${pingan.bid.printGPUrl}")
    private String printGPUrl;

    @Value("${pingan.bid.printInvoiceUrl}")
    private String printInvoiceUrl;

    @Value("${pingan.bid.endorseUrl}")
    private String endorseUrl;

    //region 获取token

    /**
     * 获取token
     *
     * @return
     */
    @Override
    public String getToken() {
        try {
            //token
            String token = tokenMap.containsKey("token") ? tokenMap.get("token") : "";
            //超时日期
            String expiresDate = tokenMap.containsKey("expiresDate") ? tokenMap.get("expiresDate") : "";
            if(StringUtils.isBlank(token) || StringUtils.isBlank(expiresDate) || (new Date().after(dateFormat.parse(expiresDate)))){
                String tokenResult = HttpUtil.get(tokenUrl);
                JSONObject resultTokenJson = JSONObject.fromObject(tokenResult);
                log.info("【平安获取token响应：{}】", resultTokenJson.toString());
                String code = resultTokenJson.getString("ret");
                if("0".equals(code)){
                    JSONObject dataJson = resultTokenJson.getJSONObject("data");
                    token = dataJson.getString("access_token");
                    tokenMap.put("token", token);
                    int minute = dataJson.getInt("expires_in");
                    DateTime outDate = DateUtil.offsetMinute(new Date(), minute);
                    tokenMap.put("expiresDate", dateFormat.format(outDate));
                    log.info("【获取平安token成功, 放入tokenMap：{}】", tokenMap.toString());
                }else{
                    log.error("【获取平安token失败, 返回空字符串】");
                    tokenMap.clear();
                    return "";
                }
            }else{
                log.info("【缓存中包含token, 且token有效：{}】", tokenMap.toString());
            }
            return token;
        } catch (Exception e) {
            log.error("【获取平安token失败】", e);
        }
        return "";
    }
    //endregion

    //region applyForFee

    /**
     * applyForFee
     *
     * @param requestBody 请求报文
     * @return
     */
    @Override
    public String applyForFee(String requestBody){
        String requestApplyForFeeUrl = applyForFeeUrl + "request_id="+ IdUtil.fastSimpleUUID()+"&access_token="+getToken();
        HttpResponse httpResponse = HttpRequest.post(requestApplyForFeeUrl)
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .header(Header.ACCEPT, "application/json;charset=utf-8 ")
                .body(requestBody).execute();
        String result = httpResponse.body();
        log.info("【平安响应报文：{}】", result);
        /**
         * {
         * "ret": "0",
         * "msg": "",
         * "requestId": "applyForFee123456789",
         * "data":{
         * "responseCode": "666666",
         * "responseMsg": "流水号：202009251801503cb8ecbb63f7489a98f9a77adf591703 重复交易",
         * "result":{"applyPolicyNo": "51077003900230858285", "policyNo": "", "noticeNo": "10150006000145296053", "totalInsuredAmount": "1,000",…}
         * }
         * }
         */
        return result;
    }
    //endregion

    //region acceptForFee

    /**
     * acceptForFee
     *
     * @param requestBody 请求报文
     * @return
     */
    @Override
    public String acceptForFee(String requestBody) {
        String requestAcceptForFeeUrl = acceptForFeeUrl + "request_id="+ IdUtil.fastSimpleUUID()+"&access_token="+getToken();
        HttpResponse httpResponse = HttpRequest.post(requestAcceptForFeeUrl)
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .header(Header.ACCEPT, "application/json;charset=utf-8 ")
                .body(requestBody).execute();
        String result = httpResponse.body();
        log.info("【平安响应报文：{}】", result);
        /**
         * {
         * "ret": "0",
         * "msg": "",
         * "requestId": "acceptForFee123456789",
         * "data":{
         * "result":{"applyPolicyNo": "51077003900230858285", "policyNo": "11077003900162941991", "noticeNo": "", "totalInsuredAmount": "1000.00",…},
         * "responseCode": "888888",
         * "responseMsg": "该投保单已承保"
         * }
         * }
         */
        return result;
    }
    //endregion

    //region 预支付订单

    /**
     * 预支付订单
     *
     * @param requestBody 请求报文
     * @return
     */
    @Override
    public String prePayFinance(String requestBody){
        String requestPrePayFinanceUrl = prePayFinanceUrl + "request_id="+ IdUtil.fastSimpleUUID()+"&access_token="+getToken();
        HttpResponse httpResponse = HttpRequest.post(requestPrePayFinanceUrl)
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .header(Header.ACCEPT, "application/json;charset=utf-8 ")
                .body(requestBody).execute();
        String result = httpResponse.body();
        log.info("【平安响应报文：{}】", result);
        /**
         * {"ret":"0","msg":"","requestId":"rq111111111","data":"{"tradeNo":"ZsRa4a14b5ae4511ae0c4af0411aa2e4","resultCode":"SUCCESS","payUrl":"https://test-pipay.pingan.com/epcis_nps/tocpcpay.do?preId=ab1d7b57699c27ccab25d222f4b960a1&cpcNoticeNo=80200939271600334580","resultMsg":"下单成功"}"}
         */
        return result;
    }
    //endregion

    @Override
    public String printGP(String requestBody){
        String requestPrintGPUrl = printGPUrl + "request_id="+ IdUtil.fastSimpleUUID()+"&access_token="+getToken();
        HttpResponse httpResponse = HttpRequest.post(requestPrintGPUrl)
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .header(Header.ACCEPT, "application/json;charset=utf-8 ")
                .body(requestBody).execute();
        String result = httpResponse.body();
        log.info("【下载点保单平安响应报文：{}】", result);
        return result;
    }

    @Override
    public String printInvoice(String requestBody){
        log.info("【平安电子发票请求报文：{}】", requestBody);
        String requestPrintInvoiceUrl = printInvoiceUrl + "request_id="+ IdUtil.fastSimpleUUID()+"&access_token="+getToken();
        log.info("【平安电子发票请求地址：{}】", requestPrintInvoiceUrl);
        HttpResponse httpResponse = HttpRequest.post(requestPrintInvoiceUrl)
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .header(Header.ACCEPT, "application/json;charset=utf-8 ")
                .body(requestBody).execute();
        String result = httpResponse.body();
        log.info("【平安电子发票响应报文：{}】", result);
        return result;
    }

    /**
     * 批改
     *
     * @param requestBody
     * @return
     */
    @Override
    public String edrSceneCode(String requestBody){
        log.info("【平安批改请求报文：{}】", requestBody);
        String requestPrintInvoiceUrl = endorseUrl + "request_id="+ IdUtil.fastSimpleUUID()+"&access_token="+getToken();
        log.info("【平安批改请求地址：{}】", requestPrintInvoiceUrl);
        HttpResponse httpResponse = HttpRequest.post(requestPrintInvoiceUrl)
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .header(Header.ACCEPT, "application/json;charset=utf-8 ")
                .body(requestBody).execute();
        String result = httpResponse.body();
        log.info("【平安批改响应报文：{}】", result);
        return result;
    }


}
